//
//  ChatViewController.m
//  000-ChatChair
//
//  Created by 李晓东 on 2018/4/20.
//  Copyright © 2018年 PeanutXu. All rights reserved.
//

#import "ChatViewController.h"
#import "AppDelegate.h"
#define ScreenWidth self.view.frame.size.width
#define ScreenHeight self.view.frame.size.height

@interface ChatViewController () <ChatDelegate, UITextFieldDelegate>
@property (nonatomic, strong) NSMutableArray *messageArray;
@property (nonatomic, strong) UITextField *inputField;
@property (nonatomic, strong) UIView *footerView;
@end

@implementation ChatViewController{
    AppDelegate *_app;
    CGRect _keyboardRect;
}

- (void)loadView {
    [super loadView];
    if (@available(iOS 11.0, *)) {
        [self.tableView setContentInsetAdjustmentBehavior:UIScrollViewContentInsetAdjustmentNever];
    }
    self.messageArray = [NSMutableArray array];
    _app = (AppDelegate *)[UIApplication sharedApplication].delegate;
    _app.chatDelegate = self;
    [self fetchHistoryMessage];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 返回按钮
    UIView *headerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 1, 55)];
    [self.tableView setTableHeaderView:headerView];
    [headerView setBackgroundColor:[UIColor redColor]];
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    [btn setFrame:CGRectMake(8, (60 - 40) / 2, 80, 40)];
    [btn setTitle:@"Back" forState:UIControlStateNormal];
    [btn setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(backClick:) forControlEvents:UIControlEventTouchUpInside];
    [headerView addSubview:btn];
    
    // 发送框
    self.footerView = [[UIView alloc]initWithFrame:CGRectMake(0, ScreenHeight - 55, ScreenWidth, 55)];
    [self.footerView setBackgroundColor:[UIColor whiteColor]];
//    [self.tableView setTableFooterView:footerView];
    self.inputField = [[UITextField alloc]initWithFrame:CGRectMake((ScreenWidth - 200) / 2, (55 - 50) / 2, 200, 40)];
    [self.inputField setPlaceholder:@"说点啥"];
    [self.inputField setBorderStyle:UITextBorderStyleRoundedRect];
    [self.inputField setReturnKeyType:UIReturnKeySend];
    [self.inputField setDelegate:self];
    [self.footerView addSubview:self.inputField];
    
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"li"];
    [self.tableView addSubview:self.footerView];
//    [self.tableView.tableFooterView addSubview:self.footerView];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(selfInputView:) name:UIKeyboardWillShowNotification object:nil];
}

- (void)fetchHistoryMessage {
    NSMutableArray *chatArray = _app.historyMessage[_session];
    if (_app.historyMessage[_session].count > 0) {
        for (DDXMLElement *element in _app.historyMessage[_session]) {
            
            [_messageArray addObject:element];
        }
    }
    
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    CGPoint point = scrollView.contentOffset;
    CGRect footFrame = self.footerView.frame;
    footFrame.origin.y = point.y + ScreenHeight - _keyboardRect.size.height - 55;
    self.footerView.frame = footFrame;
    [self.view bringSubviewToFront:_footerView];
}

- (void)selfInputView:(NSNotification *)notification {
    NSDictionary *userInfo = notification.userInfo;
    CGFloat duration = [[userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey]floatValue];
    _keyboardRect = [[userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
    [UIView animateWithDuration:duration animations:^{
        CGRect inputFrame = _footerView.frame;
        inputFrame.origin.y = ScreenHeight - _keyboardRect.size.height - 55;
        _footerView.frame = inputFrame;
    }];
}

- (void)didReceiveMessage:(XMPPMessage *)messagePath{
    dispatch_sync(dispatch_get_main_queue(), ^{
        [_messageArray addObject:messagePath];
        [self.tableView reloadData];
        
    });
    
}

- (NSString *)getCurrentSession {
    return self.session;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder];
    CGRect footFrame = self.footerView.frame;
    footFrame.origin.y = ScreenHeight - 55;
    self.footerView.frame = footFrame;
    
    NSString *message = textField.text;
    // 发送消息
    DDXMLElement *body = [DDXMLElement elementWithName:@"body"];
    [body setStringValue:message];
    // 生成<message.../>元素
    DDXMLElement* mes = [DDXMLElement elementWithName:@"message"];
    // 根据不同聊天类型设置消息类型
    if ([_session hasSuffix:ROOM_SUFFIX]) {
        [mes addAttributeWithName:@"type" stringValue:@"groupchat"];
    }else{
        [mes addAttributeWithName:@"type" stringValue:@"chat"];
    }
    
    [mes addAttributeWithName:@"to" objectValue:_session];
    [mes addAttributeWithName:@"from" objectValue:_app.xmppStream.myJID.bare];
    [mes addChild:body];
    // 发送信息
    [_app.xmppStream sendElement:mes];
    // 清空输入框
    textField.text = @"";
    [_messageArray addObject:mes];
    [self.tableView reloadData];
    return YES;
}

#pragma mark - Table view data source

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
#warning Incomplete implementation, return the number of rows
    return _messageArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"li" forIndexPath:indexPath];
    DDXMLElement *element = _messageArray[indexPath.row];
    DDXMLElement *bodyElement = [element elementForName:@"body"];
    cell.textLabel.text = bodyElement.stringValue;
    
    return cell;
}

- (void)backClick:(id)sender {
    [[NSNotificationCenter defaultCenter]removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [self dismissViewControllerAnimated:YES completion:nil];
}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
